package sg.edu.ntu.sce.sands.crypto;

import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

/**
 * 数据存储阶段
 */

public class Kmas {
    public static final int N = 4;
    private static String Kmas = null;
    public static String getKmas(int fileSize){
        String str = getRandomString(fileSize);
        String[] m = splitM(str);
        String[] k = new String[N];
        for (int i = 0; i < N; i++) {
            k[i] = BKeyGen(m[i]);

        }
        String[] c = new String[N];
        for (int i = 0; i < m.length; i++) {
            c[i] = BEnc(k[i],m[i]);
        }
        int j = 0;
        int i = 1;
        int n = N;
        int n1 = n/ 2;
        int n2 = n/ 2;
        while(true){
            for (int l = 1; l < n1; l++) {
                i = l;
                m[i] = k[2*i-1]+k[2*i];
                k[i] = BKeyGen(m[i]);
            }
            if(n1 != n2){
                m[n2] = k[n2];
            }
            for (int l = 0; l < m.length; l++) {
                c[i] = BEnc(k[i],m[i]);
            }
            j = j +1;
            n = n/2;
            n1 = n/2;
            n2 = n/2;
            if(n <= 1){
                Kmas = k[1];
                break;
            }
        }
        return Kmas;
    }
    public static String getHash(String str){
        StringBuilder h = new StringBuilder();
        MessageDigest object = null;
        byte[] encrypted = null;
        try {
            object = MessageDigest.getInstance("SHA-256");
            encrypted = object.digest(str.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (byte b : encrypted) {
            h.append(String.format("%02x", b));
        }
        return h.toString();
    }
    public static String BEnc(String encodeRules,String content){
        try {
            //1.构造密钥生成器，指定为AES算法,不区分大小写
            KeyGenerator keygen= KeyGenerator.getInstance("AES");
            //2.根据ecnodeRules规则初始化密钥生成器
            //生成一个128位的随机源,根据传入的字节数组
            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
            //3.产生原始对称密钥
            SecretKey original_key=keygen.generateKey();
            //4.获得原始对称密钥的字节数组
            byte [] raw=original_key.getEncoded();
            //5.根据字节数组生成AES密钥
            SecretKey key=new SecretKeySpec(raw, "AES");
            //6.根据指定算法AES自成密码器
            Cipher cipher=Cipher.getInstance("AES");
            //7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte [] byte_encode=content.getBytes("utf-8");
            //9.根据密码器的初始化方式--加密：将数据加密
            byte [] byte_AES=cipher.doFinal(byte_encode);
            //10.将加密后的数据转换为字符串
            //这里用Base64Encoder中会找不到包
            //解决办法：
            //在项目的Build path中先移除JRE System Library，再添加库JRE System Library，重新编译后就一切正常了。
            String AES_encode=new String(new BASE64Encoder().encode(byte_AES));
            //11.将字符串返回
            return AES_encode;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //如果有错就返加nulll
        return null;
    }
    public static String[] splitM(String str){
        int strLrn = str.length();
        String[] m = new String[N];
        int start = 0;
        int end = strLrn/N;
        int step = end;
        for (int i = 0; i < N; i++) {
            m[i] = str.substring(start,end);
            start = end;
            if(i == N- 2 ){
                end = strLrn;
            }else{
                end = end + step;
            }
        }
        return m;
    }
    public static String BKeyGen(String str){
        StringBuilder sb = new StringBuilder();
        MessageDigest object = null;
        byte[] result = null;
        try {
            object = MessageDigest.getInstance("SHA-256");
            result = object.digest(str.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (byte b : result) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    //生成指定length的随机字符串（A-Z，a-z，0-9）
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(str.length());
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

}
